package org.phalanx.servlet.websession;

import java.util.Date;
import java.util.Random;

import javax.servlet.http.Cookie;

public class SessionCookieFactory {
	public static final int SECONDS_PER_YEAR = 60*60*24*365;


	public SessionCookieFactory(){
		
	}
	
	public Cookie generateCookie(String cookieName, Integer idLength){
		Cookie newCookie = new Cookie(cookieName, generateIdKey(idLength));
		newCookie.setMaxAge(SECONDS_PER_YEAR);
		return newCookie;
	}
	
	private String generateIdKey(Integer length){
		StringBuffer idBuffer = new StringBuffer();
		Random r = new Random(new Date().getTime());
		
		for (int i = 0; i < length; i++){
			char c = (char) ((Math.abs(r.nextInt()) % ('z' - 'a')) + 'a');
			idBuffer.append(c); // all ids should be between a and z
		}
		
		return idBuffer.toString();
	}
}
